import 'models.dart';

/// Parse play sources and episodes from typical aggregation fields:
/// - `vod_play_from`: sources separated by `$$$` (e.g., "腾讯$$$优酷")
/// - `vod_play_url`: blocks separated by `$$$`, each block contains lines
///    like `EpisodeName$http://...` separated by `#` or newlines
List<PlaySource> parsePlaySources(String? playFromRaw, String? playUrlRaw) {
  if (playUrlRaw == null || playUrlRaw.isEmpty) return [];

  final sourceNames = (playFromRaw ?? '')
      .split('\$\$\$')
      .map((e) => e.trim())
      .where((e) => e.isNotEmpty)
      .toList();

  final blocks = playUrlRaw.split('\$\$\$');
  final sources = <PlaySource>[];

  for (var i = 0; i < blocks.length; i++) {
    final block = blocks[i].trim();
    if (block.isEmpty) continue;

    final episodes = <PlayEpisode>[];
    final lines = block.split(RegExp(r'[#\n]')).map((e) => e.trim()).toList();
    for (final line in lines) {
      if (line.isEmpty) continue;
      final parts = line.split(RegExp(r'\$'));
      if (parts.length >= 2) {
        final title = parts.first.trim();
        final url = parts.sublist(1).join('').trim();
        episodes.add(PlayEpisode(title.isEmpty ? '播放' : title, url));
      } else {
        // Fallback: whole line as URL
        episodes.add(PlayEpisode('播放', line));
      }
    }

    final name = i < sourceNames.length && sourceNames[i].isNotEmpty
        ? sourceNames[i]
        : '播放源${i + 1}';
    sources.add(PlaySource(name, episodes));
  }

  return sources;
}